package com.paso.security.springmvc.controller;

import com.paso.security.springmvc.model.AuthenticationRequest;
import com.paso.security.springmvc.model.UserDto;
import com.paso.security.springmvc.service.AuthenticationService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 接口
 */
@RestController
public class LoginController {

    @Resource
    private AuthenticationService authenticationService;


    /**
     * 登录
     * @param authenticationRequest
     * @param session
     * @return
     */
    @PostMapping(value = "/login", produces = "text/plain;charset=utf-8")
    public String login(AuthenticationRequest authenticationRequest, HttpSession session) {
        UserDto userDto = authenticationService.authentication(authenticationRequest);

        //存入session
        session.setAttribute(UserDto.SESSION_USER_KEY,userDto);

        return userDto.getUsername() + "登录成功";
    }

    /**
     * 退出
     * @param session
     * @return
     */
    @GetMapping(value = "logout", produces = "text/plain;charset=utf-8")
    public String logout(HttpSession session) {

        // session失效
        session.invalidate();

        return "退出成功";
    }

    /**
     * 获取用户信息，资源1
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r1", produces = "text/plain;charset=utf-8")
    public String r1(HttpSession session) {
        String fullName = null;
        Object obj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (obj == null) {
            fullName = "匿名";
        }else {
            UserDto user = (UserDto) obj;
            fullName = user.getFullName();
        }
        return fullName + "访问资源r1";
    }

    /**
     * 获取用户信息，资源2
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r2", produces = "text/plain;charset=utf-8")
    public String r2(HttpSession session) {
        String fullName = null;
        Object obj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (obj == null) {
            fullName = "匿名";
        }else {
            UserDto user = (UserDto) obj;
            fullName = user.getFullName();
        }
        return fullName + "访问资源r2";
    }
}
